# -*- coding: utf-8 -*-
"""
中文文本切分段落和句子
"""

import re


def to_paragraph(doctext):
    return [i.strip() for i in doctext.split('\n') if len(i.strip())>0]


def __merge_symmetry(sentences, symmetry=('“','”')):
    '''合并对称符号，如双引号'''
    lr = []
    is_show = False  # 前双引号是否已出现
    merged = True   # 双引号是否已配对
    for index in range(len(sentences)):
        if merged and symmetry[0] not in sentences[index] and symmetry[1] not in sentences[index]:
            lr.append(sentences[index])
        elif not is_show and merged and symmetry[0] not in sentences[index] and symmetry[1] not in sentences[index]:
            lr.append(sentences[index])
        elif symmetry[0] in sentences[index] and symmetry[1] not in sentences[index] and not is_show and merged:
            lr.append(sentences[index])
            is_show = True
            merged = False
        elif symmetry[1] in sentences[index] and symmetry[0] not in sentences[index] and is_show and not merged:
            lr[-1] += sentences[index]
            is_show = False
            merged = True
        else:
            lr[-1] += sentences[index]
    return [i.strip() for i in lr if len(i.strip()) > 0]


def to_sentences(paragraph, simple=True):
    """由段落切分成句子"""
    # 以问号、感叹号、句号、省略号切分句子
    sentences = re.split(r"(？|。|！|\…\…)", paragraph)         
    # 保留分隔符
    sentences.append("")
    sentences = ["".join(i) for i in zip(sentences[0::2], sentences[1::2])]
    sentences = [i.strip() for i in sentences if len(i.strip()) > 0]
    # 将末双引号移到前句
    for j in range(1, len(sentences)):
        if sentences[j][0] == '”':
            sentences[j-1] = sentences[j-1] + '”'
            sentences[j] = sentences[j][1:]
    if simple:
        return sentences
    return __merge_symmetry(sentences)

   


